package com.controller;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class InitSpringListener implements ServletContextListener {

    public static final String SPRING_CONTAINER_NAME = "myspring";
    private ApplicationContext context;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        String config = sce.getServletContext().getInitParameter("config");
        context = new ClassPathXmlApplicationContext(config);

        ServletContext servletContext = sce.getServletContext();
        servletContext.setAttribute(SPRING_CONTAINER_NAME, context);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        if (context != null) {
            ((ConfigurableApplicationContext) context).close();
        }
    }
}
